package controller;

import java.util.prefs.Preferences;

import view.menuelements.MenuLabel;

//Klasse zum Verwalten der Highscore-werte
public class Highscorecontroller {
	// Verknüpfung zu Preference-daten
	private Preferences prefs;

	// laenge des Highscores
	private final int LAENGE = 10;

	private long[] scores;
	private String[] names;

	public Highscorecontroller() {
		// Ort an dem Werte Gespeichert werden
		prefs = Preferences.userRoot().node("heyTetris");

		// Lädt Highscores
		scores = new long[LAENGE];
		names = new String[LAENGE];
		int zaehler = 0;
		for (String s : prefs.get("Scores", "").split(",")) {
			if (zaehler < LAENGE) {
				if (s == "") {
					scores[zaehler++] = 0;
				} else {
					scores[zaehler++] = Long.valueOf(s);
				}
			}
		}
		String[] lNames = prefs.get("Names", "").split(",");
		for (int i = 0; i < names.length && i < lNames.length; i++) {
			names[i] = lNames[i];
		}
	}

	public long getScore(int index) throws IndexOutOfBoundsException {
		return scores[index];
	}

	public String getName(int index) throws IndexOutOfBoundsException {
		return names[index];

	}

	// Prueft, ob es ein Highscore ist und faengt ihn gegebenenfalls ein
	public void addHighscore(String name, long score) {
		int zaehler = 0;
		while (zaehler < LAENGE - 1 && score <= scores[zaehler]) {
			zaehler++;
		}
		// wenn score groesser als einer aus der liste
		if (zaehler < LAENGE && score > scores[zaehler]) {

			for (int i = LAENGE - 1; i > zaehler; i--) {
				scores[i] = scores[i - 1];
				names[i] = names[i - 1];
			}
			scores[zaehler] = score;
			names[zaehler] = name;
			highscoreSpeichern();
		}
	}

	// speichert die Highscoreliste unter prevs ab
	public void highscoreSpeichern() {
		String nameList = "";
		String scoreList = "";
		for (long l : scores) {
			scoreList += l + ",";
		}
		scoreList = scoreList.substring(0, scoreList.length() - 1);
		for (String s : names) {
			if (s != null && s != "") {
				nameList += s + ",";
			} else {
				nameList += "Anonymous" + ",";
			}

		}
		nameList = nameList.substring(0, nameList.length() - 1);
		prefs.put("Names", nameList);
		prefs.put("Scores", scoreList);
	}

	public void highscoresloeschen() {
		String nameList = "";
		String scoreList = "";
		for (int i = 0; i < LAENGE - 1; i++) {
			nameList += ",";
			scoreList += ",";
		}
		prefs.put("Names", nameList);
		prefs.put("Scores", scoreList);
	}

	public int getLaenge() {
		return LAENGE;
	}
}
